/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.netbeansrcp.tasklog;

import com.netbeansrcp.taskmodel.api.Task;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import org.openide.util.LookupEvent;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
//import org.openide.util.ImageUtilities;
import org.netbeans.api.settings.ConvertAsProperties;
import org.netbeansrcp.tasksource.api.TaskSource;
import org.openide.util.Lookup;
import org.openide.util.Lookup.Result;
import org.openide.util.LookupListener;
import org.openide.util.Utilities;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.netbeansrcp.tasklog//TaskLog//EN",
autostore = false)
public final class TaskLogTopComponent extends TopComponent implements PropertyChangeListener, LookupListener {

    private DefaultListModel listModel = new DefaultListModel();

    private static TaskLogTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    private static final String PREFERRED_ID = "TaskLogTopComponent";

    private Lookup.Result<Task> result;

    public TaskLogTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(TaskLogTopComponent.class, "CTL_TaskLogTopComponent"));
        setToolTipText(NbBundle.getMessage(TaskLogTopComponent.class, "HINT_TaskLogTopComponent"));
//        setIcon(ImageUtilities.loadImage(ICON_PATH, true));

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new JList(this.listModel);

        setBackground(java.awt.Color.white);
        setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        setForeground(java.awt.Color.lightGray);
        setToolTipText(org.openide.util.NbBundle.getMessage(TaskLogTopComponent.class, "TaskLogTopComponent.toolTipText")); // NOI18N
        setAutoscrolls(true);
        setDisplayName(org.openide.util.NbBundle.getMessage(TaskLogTopComponent.class, "TaskLogTopComponent.displayName")); // NOI18N
        setFocusable(true);

        jScrollPane1.setViewportView(jList1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized TaskLogTopComponent getDefault() {
        if (instance == null) {
            instance = new TaskLogTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the TaskLogTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized TaskLogTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(TaskLogTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof TaskLogTopComponent) {
            return (TaskLogTopComponent) win;
        }
        Logger.getLogger(TaskLogTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
//        this.result = WindowManager.getDefault().findTopComponent("TaskEditorTopComponent")
//                .getLookup().lookupResult(Task.class);
        this.result = Lookup.getDefault().lookup(TaskSource.class).getLookup().lookupResult(Task.class);
//        this.result = Utilities.actionsGlobalContext().lookupResult(Task.class);
        this.result.addLookupListener(this);
        for(Task task: this.result.allInstances()){
            this.listModel.addElement(task);
            task.addPropertyChangeListener(this);
        }
    }

    @Override
    public void componentClosed() {
        for(Enumeration e = this.listModel.elements(); e.hasMoreElements();){
            ((Task)e.nextElement()).removePropertyChangeListener(this);
        }
        this.result = null;
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    Object readProperties(java.util.Properties p) {
        if (instance == null) {
            instance = this;
        }
        instance.readPropertiesImpl(p);
        return instance;
    }

    private void readPropertiesImpl(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        this.jList1.repaint();
    }

    @Override
    public void resultChanged(LookupEvent evt) {
        Lookup.Result<Task> rslt = (Result<Task>) evt.getSource();
        for(Task task: rslt.allInstances()){
            this.listModel.addElement(task);
            task.addPropertyChangeListener(this);
        }
    }
}
